<template>
  <div>
    <el-row :gutter="10">
      <el-col :span="18">
        <el-card>
          <div id="line" style="width: 100%;height: 400px"></div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card>
          <el-form :model="form" label-width="80px" style="padding-right: 50px" ref="formRefEquipment">
            <el-form-item label="选择设备" prop="equ">
              <el-select v-model="selectedEquipment" @change="updateChartData" placeholder="请选择设备">
                <el-option
                    v-for="item in equimentOption"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="查看方式" prop="granularity">
              <el-select v-model="selectedGranularity" @change="updateChartData" placeholder="请选择查看方式">
                <el-option label="按天查看" value="day"></el-option>
                <el-option label="按周查看" value="week"></el-option>
                <el-option label="按月查看" value="month"></el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>
  </div>

</template>

<script>
import * as echarts from 'echarts'

const option = {
  title: {
    text: '水量统计',
  },
  tooltip: {
    trigger: 'axis',
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: []
  },
  yAxis: {
    type: 'value',
    axisLabel: {
      formatter: '{value} L'
    },
    axisPointer: {
      snap: true
    }
  },
  series: [
    {
      name: '使用水量',
      type: 'line',
      smooth: true,
      data: []
    }
  ]
}
export default {
  name: "Charts",
  data() {
    return {
      user: JSON.parse(localStorage.getItem('base-user') || '{}'),
      equimentOption: [],
      selectedEquipment: '',
      form: {},
      chartsData: [],
      lineChart: null,// 存储ECharts实例
      selectedGranularity: 'day',
      chartsRawData: {}, // 用于存储从后端接收的原始数据
      formattedChartsData: [], // 用于存储格式化后的数据，供 ECharts 使用
      weeklyDate: false,
    }
  },
  mounted() {//页面元素全部加载完成后初始化
    //折线图
    let lineDom = document.getElementById('line')
    this.lineChart = echarts.init(lineDom)

    this.$request.get('/charts', {granularity: this.selectedGranularity}).then(res => {
      this.chartsRawData = res.data; // 存储原始数据
      this.formatAndSortChartData(); // 格式化并排序数据
      this.setChartOptionData(); // 设置图表数据
      this.selectUniqueEquipment(); // 选择唯一设备
      this.lineChart.setOption(option); // 初始化图表
    })

  },
  methods: {
    formatAndSortChartData() {
      this.formattedChartsData = [];

      if (this.weeklyDate) {
        // 第一段代码逻辑，处理周数据
        for (const device in this.chartsRawData) {
          if (this.chartsRawData.hasOwnProperty(device)) {
            const deviceData = this.chartsRawData[device];
            for (const dateStr in deviceData) {
              if (deviceData.hasOwnProperty(dateStr)) {
                const [year, week] = dateStr.split('-W').map(Number);
                const formattedDate = `${year}年第${week}周`;

                this.formattedChartsData.push({
                  equName: device,
                  date: formattedDate,
                  useCount: deviceData[dateStr],
                  rawDate: dateStr,
                });
              }
            }
          }
        }

        // 排序数据：按周数排序（使用原始日期字符串进行排序）
        this.formattedChartsData.sort((a, b) => {
          const [aYear, aWeek] = a.rawDate.split('-W').map(Number);
          const [bYear, bWeek] = b.rawDate.split('-W').map(Number);
          if (aYear === bYear) {
            return aWeek - bWeek;
          } else {
            return aYear - bYear;
          }
        });

        // 如果不需要保留 rawDate，可以取消注释以下行
        this.formattedChartsData = this.formattedChartsData.map(item => ({...item, rawDate: undefined}));

      } else {
        // 第二段代码逻辑，处理日数据
        for (const device in this.chartsRawData) {
          if (this.chartsRawData.hasOwnProperty(device)) {
            const deviceData = this.chartsRawData[device];
            for (const date in deviceData) {
              if (deviceData.hasOwnProperty(date)) {
                this.formattedChartsData.push({
                  equName: device,
                  date: date,
                  useCount: deviceData[date],
                });
              }
            }
          }
        }

        // 排序数据：按日期排序
        this.formattedChartsData.sort((a, b) => new Date(a.date) - new Date(b.date));
      }
    },
    selectUniqueEquipment() {
      const uniqueNames = new Set(this.formattedChartsData.map(item => item.equName));
      this.equimentOption = [...uniqueNames].map(name => ({
        value: name,
        label: name,
      }));

      // 如果没有预设的设备选择，则选择第一个设备
      if (this.equimentOption.length > 0) {
        this.selectedEquipment = this.equimentOption[0].value;
        this.updateChartData(); // 初始化时更新图表数据
      }
    },
    setChartOptionData() {
      // 初始化图表数据：选择第一个设备的数据
      if (this.formattedChartsData.length > 0 && this.equimentOption.length > 0) {
        this.selectedEquipment = this.equimentOption[0].value; // 默认选择第一个设备
        const filteredData = this.formattedChartsData.filter(item => item.equName === this.selectedEquipment);
        option.xAxis.data = filteredData.map(v => v.date);
        option.series[0].data = filteredData.map(v => v.useCount);
      } else {
        // 如果没有数据或设备选项，则清空图表数据
        option.xAxis.data = [];
        option.series[0].data = [];
      }
    },
    updateChartData() {
      // 清除之前的数据
      this.chartsRawData = {};
      this.formattedChartsData = [];

      // 根据新的粒度重新获取数据
      this.$request.get('/charts', {
        params: {
          granularity: this.selectedGranularity
        }
      }).then(res => {
        this.chartsRawData = res.data; // 存储原始数据
        this.weeklyDate = (this.selectedGranularity === 'week'); // 根据选择的粒度设置 weeklyDate
        this.formatAndSortChartData(); // 格式化并排序数据

        // 更新图表数据
        const filteredData = this.formattedChartsData.filter(item => item.equName === this.selectedEquipment);
        option.xAxis.data = filteredData.map(v => v.date);
        option.series[0].data = filteredData.map(v => v.useCount);
        this.lineChart.setOption(option); // 更新图表
      });
    },
  }
}
</script>

<style scoped>

</style>